package br.ufpe.cin.dsoa.qos.service.registry.impl;

import java.util.ArrayList;
import java.util.List;

public class RollingList {

	private List<Data> items;
	private int capacity;

	public RollingList(final int capacity) {
		this.capacity = capacity;
		this.items = new ArrayList<Data>();
	}

	public void add(Data e) {
		if (items.size() > capacity - 1) {
			items.remove(0);
		}
		items.add(e);
	}

	public void add(List<Data> l) {
		this.items.addAll(l);
	}

	public List<Data> getList() {
		return this.items;
	}

	public double[] getData() {
		double[] data = new double[items.size()];

		for (int i = 0; i < data.length; i++) {
			data[i] = items.get(i).getValue();
		}
		return data;
	}

	public double[] getData(int windowSize) {
		int size = windowSize > items.size() ? items.size() : windowSize;
		double[] data = new double[size];

		for (int i = 1; i <= size; i++) {
			data[size - i] = items.get(items.size() - i).getValue();
		}

		return data;
	}

	public double[] getData(long secondsAgo) {
		long now = System.currentTimeMillis();
		long mili = secondsAgo * 1000;
		
		List<Double> data = new ArrayList<Double>();
		for (Data d : items) {
			if (now - d.getTimestamp() <= mili) {
				data.add(d.getValue());
			} else {
				break;
			}
		}
		
		double[] filtred = new double[data.size()];
		int i = 0;
		for (Double d : data) {
			filtred[i++] = d;
		}
		return filtred;
	}

	public int size() {
		return items.size();
	}

	public int capacity() {
		return capacity;
	}
}